package org.demo.hbase.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;
import org.demo.hbase.tools.HBaseTools;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HBaseController {

	@GetMapping("all")
	public static List<Map<String, String>> getAllRows() throws Exception {
		List<Map<String, String>> arrayList = new ArrayList<>();
		Table table = HBaseTools.getConnection().getTable(TableName.valueOf("test:zxy"));
		Scan scan = new Scan();
//		scan.addFamily(Bytes.toBytes("abc"));
		ResultScanner resultScanner = table.getScanner(scan);
		for (Result result : resultScanner) {
			Cell[] cells = result.rawCells();
			for (Cell cell : cells) {
				Map<String, String> hashMap = new HashMap<String, String>();
				hashMap.put("family", Bytes.toString(CellUtil.cloneFamily(cell)));
				hashMap.put("id", Bytes.toString(CellUtil.cloneRow(cell)));
				hashMap.put(Bytes.toString(CellUtil.cloneQualifier(cell)), Bytes.toString(CellUtil.cloneValue(cell)));
				arrayList.add(hashMap);
			}
		}
		return arrayList;
	}

	@GetMapping("getRow")
	public static List<Map<String, String>> getRow() throws Exception {
		List<Map<String, String>> arrayList = new ArrayList<>();
		Table table = HBaseTools.getConnection().getTable(TableName.valueOf("test:zxy"));
		Get get = new Get(Bytes.toBytes("1002"));
		Result result = table.get(get);
		for (Cell cell : result.rawCells()) {
			Map<String, String> hashMap = new HashMap<String, String>();
			hashMap.put("family", Bytes.toString(CellUtil.cloneFamily(cell)));
			hashMap.put("id", Bytes.toString(CellUtil.cloneRow(cell)));
			hashMap.put(Bytes.toString(CellUtil.cloneQualifier(cell)), Bytes.toString(CellUtil.cloneValue(cell)));
			arrayList.add(hashMap);
		}
		return arrayList;
	}
}
